package com.zhihaoliang.coroutine.buss.channel.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @author 支豪亮
 * @date 2022/10/28 09:38
 * @des "Channels are fair
 */
object ChannelFair {

    data class Ball(var hits: Int)

    fun showChannelFair(mainScope:CoroutineScope) = mainScope.launch {
        val table = Channel<Ball>() // a shared table
        launch { player("ping", table) }
        launch { player("pong", table) }
        table.send(Ball(0)) // serve the ball
        delay(1000) // delay 1 second
        coroutineContext.cancelChildren() // game over, cancel them
    }

    suspend fun player(name: String, table: Channel<Ball>) {
        for (ball in table) { // receive the ball in a loop
            ball.hits++
            log("$name $ball")
            delay(300) // wait a bit
            table.send(ball) // send the ball back
        }
    }
}